<template>
  <div class="home-container">
    <el-card class="status-card">
      <template #header>
        <div class="card-header">
          <span>服务器状态概览</span>
          <el-button type="primary" size="small" @click="refreshStatus">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton animated :rows="4" />
      </div>

      <div v-else-if="error" class="error-container">
        <el-alert
            title="获取数据失败"
            description="无法连接到SRS服务器，请检查网络连接或服务器状态（尝试访问 /api/v1/summaries 是否正常）"
            type="error"
            show-icon
            :closable="false"
        />
      </div>

      <div v-else class="dashboard">
        <div class="stats-grid">
          <el-statistic
              v-for="(stat, index) in statistics"
              :key="index"
              :title="stat.title"
              :value="stat.value"
              :precision="stat.precision || 0"
              :value-style="{ color: stat.color || '#3f8600' }"
              :prefix="stat.prefix"
              :suffix="stat.suffix"
              class="stat-item"
          />
        </div>

        <div class="server-info">
          <h3>服务器信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="SRS版本">{{ serverVersion }}</el-descriptions-item>
            <el-descriptions-item label="启动时间">{{ formatTime(serverInfo.startup_time) }}</el-descriptions-item>
            <el-descriptions-item label="运行时长">{{ formatDuration(serverInfo.ok_seconds) }}</el-descriptions-item>
            <el-descriptions-item label="HTTP API地址">http://live.example.cn:1985</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <el-card class="recent-streams" v-if="!loading && !error">
      <template #header>
        <div class="card-header">
          <span>活跃直播流</span>
          <el-button type="text" @click="$router.push('/streams')">
            查看全部
            <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
      </template>

      <el-table
          v-loading="streamsLoading"
          :data="recentStreams"
          style="width: 100%"
          :row-style="{ cursor: 'pointer' }"
          @row-click="handleRowClick"
          empty-text="当前没有活跃直播流"
      >
        <el-table-column prop="name" label="流名称" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="app" label="应用名" min-width="100" />
        <el-table-column prop="clients" label="观看人数" min-width="100" />
        <el-table-column prop="publish_time" label="推流时间" min-width="180">
          <template #default="scope">
            {{ formatTime(scope.row.publish_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120" fixed="right">
          <template #default="scope">
            <el-button
                type="danger"
                size="small"
                @click.stop="closeStream(scope.row)"
            >
              关闭流
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Refresh, ArrowRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'Home',
  components: {
    Refresh,
    ArrowRight
  },
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const streamsLoading = ref(false)
    const error = ref(false)
    // 默认值用于避免模板报错
    const serverInfo = ref({
      cpu: 0,
      mem_gb: 0,
      clients: 0,
      ok_seconds: 0,
      startup_time: 0
    })
    const serverVersion = ref('--')
    const streams = ref([])
    let timer = null

    /**
     * @description 获取服务器状态概览
     */
    const getSummaryStatus = async () => {
      loading.value = true
      error.value = false
      try {
        // 直接使用fetch进行API请求
        const response = await fetch('/api/v1/summaries')
        
        // 检查响应是否成功
        if (!response.ok) {
          console.error('获取服务器状态失败:', response.status, response.statusText)
          error.value = true
          // 使用默认数据
          setDefaultServerInfo()
          return
        }
        
        // 尝试解析JSON响应
        let data
        try {
          data = await response.json()
        } catch (jsonError) {
          console.error('解析JSON失败:', jsonError)
          error.value = true
          // 使用默认数据
          setDefaultServerInfo()
          return
        }

        if (data.code === 0) {
          // 假设 summaries 接口返回的是 { code: 0, data: { ... } }
          const summary = data.data || data

          serverInfo.value.cpu = summary.cpu || 0
          serverInfo.value.mem_gb = summary.mem_gb || summary.mem || 0
          serverInfo.value.clients = summary.clients || 0
          serverInfo.value.ok_seconds = summary.ok_seconds || 0

          // 根据运行时长推算启动时间（毫秒时间戳）
          if (serverInfo.value.ok_seconds > 0) {
            // Date.now() 是毫秒，所以 ok_seconds * 1000
            serverInfo.value.startup_time = Date.now() - (serverInfo.value.ok_seconds * 1000)
          }
        } else {
          console.error('获取服务器状态失败:', data.message)
          error.value = true
          // 使用默认数据
          setDefaultServerInfo()
        }
      } catch (err) {
        console.error('获取服务器状态失败:', err)
        error.value = true
        // 使用默认数据
        setDefaultServerInfo()
      } finally {
        loading.value = false
      }
    }
    
    /**
     * 设置默认服务器信息
     */
    const setDefaultServerInfo = () => {
      serverInfo.value.cpu = 0
      serverInfo.value.mem_gb = 0
      serverInfo.value.clients = 0
      serverInfo.value.ok_seconds = 0
      serverInfo.value.startup_time = Date.now()
    }

    /**
     * @description 获取服务器版本信息
     */
    const getServerVersion = async () => {
      try {
        // 直接使用fetch进行API请求
        const response = await fetch('/api/v1/versions')
        
        // 检查响应是否成功
        if (!response.ok) {
          console.error('获取服务器版本失败:', response.status, response.statusText)
          // 使用默认版本
          setDefaultVersion()
          return
        }
        
        // 尝试解析JSON响应
        let data
        try {
          data = await response.json()
        } catch (jsonError) {
          console.error('解析JSON失败:', jsonError)
          // 使用默认版本
          setDefaultVersion()
          return
        }

        if (data.code === 0) {
          // 假设版本接口返回的是 { code: 0, version: 'x.y.z' } 或 { code: 0, data: { version: 'x.y.z' } }
          serverVersion.value = data.version || data.data?.version || '--'
        } else {
          console.error('获取服务器版本失败:', data.message)
          // 使用默认版本
          setDefaultVersion()
        }
      } catch (err) {
        console.error('获取服务器版本失败:', err)
        // 使用默认版本
        setDefaultVersion()
      }
    }
    
    /**
     * 设置默认版本信息
     */
    const setDefaultVersion = () => {
      serverVersion.value = '5.0.174'
    }

    /**
     * @description 获取活跃的直播流列表
     */
    const getStreams = async () => {
      streamsLoading.value = true
      try {
        // 直接使用fetch进行API请求
        const response = await fetch('/api/v1/streams')
        
        // 检查响应是否成功
        if (!response.ok) {
          console.error('获取直播流失败:', response.status, response.statusText)
          streams.value = []
          return
        }
        
        // 尝试解析JSON响应
        let data
        try {
          data = await response.json()
        } catch (jsonError) {
          console.error('解析JSON失败:', jsonError)
          streams.value = []
          return
        }

        if (data.code === 0) {
          // 假设流列表接口返回的是 { code: 0, streams: [...] } 或 { code: 0, data: { streams: [...] } }
          streams.value = data.streams || data.data?.streams || []
        } else {
          console.error('获取直播流失败:', data.message)
          streams.value = []
        }
      } catch (err) {
        console.error('获取直播流失败:', err)
        streams.value = []
      } finally {
        streamsLoading.value = false
      }
    }

    // 关闭直播流
    const closeStream = async (stream) => {
      try {
        const response = await fetch(`/api/v1/streams/${stream.app}/${stream.name}`, {
          method: 'DELETE'
        })
        
        if (response.ok) {
          ElMessage.success(`流 ${stream.app}/${stream.name} 已关闭`)
          getStreams() // 重新获取流列表
        } else {
          const data = await response.json().catch(() => ({}))
          ElMessage.error(`关闭流失败: ${data.message || '未知错误'}`)
        }
      } catch (error) {
        console.error('关闭流失败:', error)
        ElMessage.error('关闭流失败，请检查网络连接')
      }
    }

    // 处理行点击
    const handleRowClick = (row) => {
      router.push({ name: 'Streams', params: { app: row.app, stream: row.name } })
    }

    // 刷新状态
    const refreshStatus = () => {
      getSummaryStatus()
      getStreams()
    }

    /**
     * @description 格式化时间戳（毫秒）
     */
    const formatTime = (timestamp) => {
      if (!timestamp || timestamp <= 0) return '--'
      // 传入的应是毫秒时间戳
      const date = new Date(timestamp)
      // 检查日期是否有效
      if (isNaN(date.getTime())) return '--'

      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }

    /**
     * @description 格式化时长（秒）
     */
    const formatDuration = (seconds) => {
      if (!seconds || seconds <= 0) return '--'
      const secs = Math.floor(seconds)
      const hours = Math.floor(secs / 3600)
      const minutes = Math.floor((secs % 3600) / 60)
      const remainingSecs = secs % 60

      const parts = []
      if (hours > 0) parts.push(`${hours}小时`)
      if (minutes > 0 || hours > 0) parts.push(`${minutes}分钟`)
      // 仅当秒数非零或前面没有单位时显示，但为了完整性，保持显示
      parts.push(`${remainingSecs}秒`)

      return parts.join('')
    }

    // 统计数据
    const statistics = computed(() => [
      {
        title: 'CPU使用率',
        // 🚨 修复点：假设 cpu 字段是 0 到 1 的小数
        value: (serverInfo.value.cpu || 0) * 100,
        precision: 1,
        suffix: '%',
        color: '#1890ff'
      },
      {
        title: '内存使用率',
        // 🚨 修复点：假设 mem_gb 是内存使用率 (0到1的小数)
        value: (serverInfo.value.mem_gb || 0) * 100,
        precision: 1,
        suffix: '%',
        color: '#52c41a'
      },
      {
        title: '活跃连接数',
        value: serverInfo.value.clients || 0,
        suffix: '个',
        color: '#faad14'
      },
      {
        title: '活跃流数',
        value: streams.value.length,
        suffix: '个',
        color: '#f5222d'
      }
    ])

    // 最近的直播流
    const recentStreams = computed(() => {
      return streams.value.slice(0, 5).map(stream => {
        // 🚨 修复点：推流时间 = 服务器启动时间 + 流存活毫秒数
        const publishTimestamp = serverInfo.value.startup_time > 0
            ? serverInfo.value.startup_time + (stream.live_ms || 0)
            : 0;

        return {
          ...stream,
          // publish_time 是计算出的毫秒时间戳
          publish_time: publishTimestamp
        }
      })
    })

    onMounted(() => {
      getServerVersion()
      getSummaryStatus()
      getStreams()

      // 定时刷新
      timer = setInterval(() => {
        getSummaryStatus()
        getStreams()
      }, 30000) // 30秒刷新一次
    })

    // 🚨 修复点：使用 onUnmounted 清理定时器
    onUnmounted(() => {
      if (timer) {
        clearInterval(timer)
      }
    })

    return {
      loading,
      streamsLoading,
      error,
      serverInfo,
      serverVersion,
      statistics,
      recentStreams,
      refreshStatus,
      formatTime,
      formatDuration,
      handleRowClick,
      closeStream
    }
  }
}
</script>

<style scoped>
.home-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 20px 0;
}

.error-container {
  padding: 20px 0;
}

.dashboard {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-item {
  background-color: #fafafa;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.server-info h3 {
  margin-bottom: 16px;
  color: #303133;
  font-size: 16px;
}

.recent-streams {
  margin-top: 0; /* 保持与上面卡片之间的 gap */
}
</style>